package com.ydlclass.compress.Impl;

import com.ydlclass.compress.Compressor;
import com.ydlclass.exceptions.CompressException;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * 压缩解压缩的实现
 * @Author duWenJian
 * @Date 2023/11/3 21:32
 * @Version 1.0
 */
@Slf4j
public class GzipCompress implements Compressor {
    @Override
    public byte[] compress(byte[] data) {
        if (data == null){
            return null;
        }
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos);){
            gzipOutputStream.write(data);
            gzipOutputStream.finish();
            if (log.isDebugEnabled()){
                log.debug("压缩前的字节数组长度为{}压缩后的字节数组长度为：{}",data.length,baos.toByteArray().length);
            }
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("对字节数组进行压缩发横异常",e);
            throw new CompressException("gzip压缩失败");
        }
    }

    @Override
    public byte[] decompress(byte[] data) {
        if (data == null){
            return null;
        }
        try ( ByteArrayInputStream bais = new ByteArrayInputStream(data);
              GZIPInputStream gzipInputStream = new GZIPInputStream(bais);) {
            byte[] bytes = gzipInputStream.readAllBytes();
            if (log.isDebugEnabled()){
                log.debug("解压前的字节数组长度为{},解压后的字节数组长度为：{}",data.length,bytes.length);
            }
            return bytes;
        } catch (IOException e) {
            throw new CompressException("gzip解压缩压缩失败");
        }

    }

    public static void main(String[] args) {
        byte[] bytes = new byte[]{1,2,35,6,7,8,9,10};
        GzipCompress gzipCompress = new GzipCompress();
        byte[] compress = gzipCompress.compress(bytes);
        System.out.println("压缩前的数据为:"+ Arrays.toString(bytes));
        System.out.println("压缩后的数据为:"+Arrays.toString(compress));
        System.out.println("--------------------------------------------------");
        byte[] decompress = gzipCompress.decompress(compress);
        System.out.println("解压后的数据为:"+Arrays.toString(decompress));
    }
}
